package com.ruijie.autotest.log.common.crypto;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

public class DES_ECB implements CipherInitializer {
	public static final String NAME = "DES/ECB/PKCS5Padding";

	private final String password;

	private DES_ECB(String password) {
		this.password = password;
	}

	@Override
	public Cipher createCipher(int cryptoMode) {
		try {
			Cipher result = Cipher.getInstance(NAME);
			result.init(cryptoMode,
					SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(password.getBytes())));
			return result;
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidKeySpecException e) {
			throw new RuntimeException("failed to create cipher. ", e);
		}
	}

	public static DES_ECB of(String password) {
		return new DES_ECB(password);
	}
}
